package top.lixunda.common.validate.validate;

import lombok.extern.slf4j.Slf4j;
import top.lixunda.common.validate.annotation.XumDefaultToNull;
import top.lixunda.common.validate.core.ValidateError;
import top.lixunda.common.validate.exception.XumValidException;

import java.lang.annotation.Annotation;
import java.lang.reflect.Field;

/**
 * @author Xumda
 * @version time:2019/12/9 13:15
 * <p>
 * 当数值为0，字符串为空字符串，浮点型为0.0时更改参数为null，需要包装类型
 * 此注解用于更新数据时防止空字符串清空原来字段数据
 */
@Slf4j
public class DefaultToNullValidate implements AnnotationValidate {

    @Override
    public boolean support(Class annotationClass) {
        return XumDefaultToNull.class.equals(annotationClass);
    }

    @Override
    public ValidateError valid(Annotation annotation, Field field, Object obj, Object value, AnnotationCacheValidate handler) {
        if (value == null) {
            return null;
        }
        try {
            if (value instanceof String) {
                if ("".equals(value)) {
                    field.setAccessible(true);
                    field.set(obj, null);
                }
                return null;
            }
            if (value instanceof Integer) {
                if ((int) value == 0) {
                    field.setAccessible(true);
                    field.set(obj, null);
                }
                return null;
            }
            if (value instanceof Long) {
                if ((long) value == (long) 0) {
                    field.setAccessible(true);
                    field.set(obj, null);
                }
                return null;
            }
            if (value instanceof Short) {
                if ((short) value == (short) 0) {
                    field.setAccessible(true);
                    field.set(obj, null);
                }
                return null;
            }
            if (value instanceof Float) {
                if ((float) value == (float) 0.0) {
                    field.setAccessible(true);
                    field.set(obj, null);
                }
                return null;
            }
            if (value instanceof Double) {
                if ((double) value == 0.0) {
                    field.setAccessible(true);
                    field.set(obj, null);
                }
                return null;
            }
        } catch (IllegalAccessException e) {
            e.printStackTrace();
            log.error("设置值失败，请修复异常");
            throw new XumValidException("参数验证错误，设置值失败");
        }
        return null;
    }


}
